package com.financing.wap.web.filter;

import com.financing.wap.common.ResultMap;
import com.financing.wap.util.IPUtil;
import com.financing.wap.util.MemcacheCacheHelper;
import net.sf.json.JSONObject;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * Servlet Filter implementation class AccessFilter
 */
@Component(value="antiBrushFilter")
public class AntiBrushFilter implements Filter{

	private static final String[] ANTI_BRUSH_URL = {
			".*/api/otp/.*"
	};

	private String encoding = null;

	protected final org.slf4j.Logger log = LoggerFactory.getLogger(AntiBrushFilter.class);

	private static String CONTEXT_PATH = "";

	public static String ipBmd = "101.88.233.101,203.156.233.216";

	@Override
	public void destroy() {
		log.debug("destroy login filter");

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
						 FilterChain filterChain) throws IOException, ServletException {


		HttpServletRequest httpRequest =  (HttpServletRequest)request;
		String ip = IPUtil.getRemoteHost(httpRequest);
		String requestUri = httpRequest.getRequestURI();
		if(!needLogin(requestUri) && !ipBmd.contains(ip)){

			log.info("AntiBrushFilterIp:"+ip);

			//每个ip
			Integer ip_i  = (Integer) MemcacheCacheHelper.mcc.get(ip+"i");
			Boolean ip_ab  = (Boolean) MemcacheCacheHelper.mcc.get(ip+"ab");
			Date ip_time = (Date) MemcacheCacheHelper.mcc.get(ip+"abTime");
			Integer ip_optFrequency = 3;
			Long ip_optTimeOut = 10*1000L;
			Long ip_opt_sleep = 7*60*60*24*1000L;
			Date now = new Date();

			log.info("AntiBrushFilterIp:ip_i:"+ip_i);

			log.info("AntiBrushFilterIp:ip_time:"+ip_time);

			if(ip_ab == null ){
				ip_ab =  false;
			}

			if(ip_i == null || ip_time == null){

				MemcacheCacheHelper.mcc.set(ip+"abTime", new Date());
				MemcacheCacheHelper.mcc.set(ip+"i", 1);
				filterChain.doFilter(request, response);
				return;
			}else if(ip_i >= ip_optFrequency && (now.getTime() - ip_time.getTime() < ip_optTimeOut)){  //超过10条低于10秒
				log.error("ip antiBrush is true;"+ip);
				MemcacheCacheHelper.mcc.set(ip+"ab",true);
			}else if(ip_i >= ip_optFrequency && (now.getTime() - ip_time.getTime() > ip_optTimeOut)){

				////超过10条高于10秒  还没拉黑  时间重置
				if(ip_ab != null && !ip_ab){
					MemcacheCacheHelper.mcc.set(ip+"abTime", new Date());
				}
			}else{
				log.info("AntiBrushFilterIp:5");
				MemcacheCacheHelper.mcc.set(ip+"i", ip_i+1);
			}
			if(ip_ab != null && ip_ab ) {
				if (now.getTime() - ip_time.getTime() > ip_opt_sleep) {
					MemcacheCacheHelper.mcc.set(ip + "ab", false);
					MemcacheCacheHelper.mcc.set(ip + "i", 1);
					MemcacheCacheHelper.mcc.set(ip + "abTime", new Date());

				} else {
					log.error("ip antiBrush;"+ip);
					ResultMap result = new ResultMap();
					result.setStatus(ResultMap.STATUS.SUCCESS);
					result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
					result.setAttribute("AB", "AB");//反刷标识
					PrintWriter pw = response.getWriter();
					pw.write(JSONObject.fromObject(result).toString());
					return;
				}

			}

		}



		filterChain.doFilter(request, response);
	}

	/**
	 * 判断当前请求是否需要登陆
	 * @param requestUri
	 */
	private boolean needLogin(String requestUri){
		/**
		 * 排除满足正则的URL
		 */
		for(int i=0; i < ANTI_BRUSH_URL.length; i++){
			String regex = ANTI_BRUSH_URL[i];
			if(requestUri.matches(regex)){
				return false;
			}
		}

		return true;
	}

	/**
	 * 初始化Filter
	 */
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}
}
